package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.InterfaceExtension;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.classfile.MethodSignature;
import java.lang.reflect.Method;
import java.time.LocalDate;

/**
 *  自定义切面，用于公共字段填充
 */

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     *  切入点
     */

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointcut(){

    }

    /**
     *  前置通知,进行公共字段的赋值
     */

    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段填充");

        //获取到当前被拦截的数据库的类型
        org.aspectj.lang.reflect.MethodSignature signature = (org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature();//方法签名对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的AutoFill注解对象
        OperationType value = autoFill.value(); //获得数据库操作类型

        //获取到当前被拦截的方法的参数--实体对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        Object object = args[0];

        //准备赋值数据
        LocalDate localDate = LocalDate.now();
        Long currentTime = System.currentTimeMillis();

        //根据当前不同的操作类型，为对应的属性通过反射来赋值
        if (value == OperationType.INSERT){
            //为四个公共字段赋值
            try {
                object.getClass().getDeclaredMethod("setCreateTime", LocalDate.class).invoke(object, localDate);
                object.getClass().getDeclaredMethod("setUpdateTime", LocalDate.class).invoke(object, localDate);
                object.getClass().getDeclaredMethod("setCreateUser", Long.class).invoke(object, currentTime);
                object.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(object, currentTime);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }else if (value == OperationType.UPDATE){
            //为两个公共字段赋值
            try {
                object.getClass().getDeclaredMethod("setUpdateTime", LocalDate.class).invoke(object, localDate);
                object.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(object, currentTime);
            }
            catch (Exception e) {
                e.printStackTrace();
            }

        }


    }
}
